package com.reactim.user.controller;

import com.reactim.user.entity.FriendGroup;
import com.reactim.user.service.FriendGroupService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 好友分组控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/friend-groups")
@RequiredArgsConstructor
public class FriendGroupController {
    
    private final FriendGroupService friendGroupService;
    
    /**
     * 创建好友分组
     */
    @PostMapping
    public ResponseEntity<FriendGroupResponse> createGroup(@Valid @RequestBody CreateGroupDto request) {
        FriendGroup group = friendGroupService.createGroup(
                request.getUserId(), 
                request.getName(), 
                request.getDescription()
        );
        
        FriendGroupResponse response = convertToResponse(group);
        
        log.info("创建好友分组成功: userId={}, groupName={}", request.getUserId(), request.getName());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 更新好友分组
     */
    @PutMapping("/{groupId}")
    public ResponseEntity<FriendGroupResponse> updateGroup(
            @PathVariable Long groupId,
            @Valid @RequestBody UpdateGroupDto request) {
        
        FriendGroup group = friendGroupService.updateGroup(
                groupId, 
                request.getUserId(), 
                request.getName(), 
                request.getDescription()
        );
        
        FriendGroupResponse response = convertToResponse(group);
        
        log.info("更新好友分组成功: groupId={}, newName={}", groupId, request.getName());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 删除好友分组
     */
    @DeleteMapping("/{groupId}")
    public ResponseEntity<Void> deleteGroup(
            @PathVariable Long groupId,
            @RequestParam Long userId) {
        
        friendGroupService.deleteGroup(groupId, userId);
        
        log.info("删除好友分组成功: groupId={}, userId={}", groupId, userId);
        
        return ResponseEntity.ok().build();
    }
    
    /**
     * 获取用户的所有分组
     */
    @GetMapping
    public ResponseEntity<List<FriendGroupResponse>> getUserGroups(@RequestParam Long userId) {
        List<FriendGroup> groups = friendGroupService.getUserGroups(userId);
        
        List<FriendGroupResponse> responses = groups.stream()
                .map(this::convertToResponse)
                .toList();
        
        return ResponseEntity.ok(responses);
    }
    
    /**
     * 调整分组排序
     */
    @PostMapping("/reorder")
    public ResponseEntity<Void> reorderGroups(@Valid @RequestBody ReorderGroupsDto request) {
        friendGroupService.reorderGroups(request.getUserId(), request.getGroupIds());
        
        log.info("调整好友分组排序成功: userId={}, groupCount={}", 
                request.getUserId(), request.getGroupIds().size());
        
        return ResponseEntity.ok().build();
    }
    
    /**
     * 移动好友到分组
     */
    @PostMapping("/move-friend")
    public ResponseEntity<Void> moveFriendToGroup(@Valid @RequestBody MoveFriendDto request) {
        friendGroupService.moveFriendToGroup(
                request.getUserId(), 
                request.getFriendId(), 
                request.getGroupId()
        );
        
        log.info("移动好友到分组成功: userId={}, friendId={}, groupId={}", 
                request.getUserId(), request.getFriendId(), request.getGroupId());
        
        return ResponseEntity.ok().build();
    }
    
    /**
     * 批量移动好友到分组
     */
    @PostMapping("/move-friends")
    public ResponseEntity<Void> moveFriendsToGroup(@Valid @RequestBody MoveFriendsDto request) {
        friendGroupService.moveFriendsToGroup(
                request.getUserId(), 
                request.getFriendIds(), 
                request.getGroupId()
        );
        
        log.info("批量移动好友到分组成功: userId={}, friendCount={}, groupId={}", 
                request.getUserId(), request.getFriendIds().size(), request.getGroupId());
        
        return ResponseEntity.ok().build();
    }
    
    /**
     * 获取分组中的好友数量
     */
    @GetMapping("/{groupId}/friend-count")
    public ResponseEntity<FriendCountResponse> getFriendCountInGroup(
            @PathVariable Long groupId,
            @RequestParam Long userId) {
        
        long count = friendGroupService.getFriendCountInGroup(userId, groupId);
        
        FriendCountResponse response = new FriendCountResponse();
        response.setCount(count);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 转换为响应对象
     */
    private FriendGroupResponse convertToResponse(FriendGroup group) {
        FriendGroupResponse response = new FriendGroupResponse();
        response.setId(group.getId());
        response.setUserId(group.getUserId());
        response.setName(group.getName());
        response.setDescription(group.getDescription());
        response.setSortOrder(group.getSortOrder());
        response.setIsDefault(group.getIsDefault());
        response.setIsSystem(group.getIsSystem());
        response.setCreatedAt(group.getCreatedAt());
        response.setUpdatedAt(group.getUpdatedAt());
        return response;
    }
    
    // DTO classes
    
    @Data
    public static class CreateGroupDto {
        @NotNull(message = "用户ID不能为空")
        private Long userId;
        
        @NotBlank(message = "分组名称不能为空")
        @Size(max = 50, message = "分组名称不能超过50个字符")
        private String name;
        
        @Size(max = 200, message = "分组描述不能超过200个字符")
        private String description;
    }
    
    @Data
    public static class UpdateGroupDto {
        @NotNull(message = "用户ID不能为空")
        private Long userId;
        
        @NotBlank(message = "分组名称不能为空")
        @Size(max = 50, message = "分组名称不能超过50个字符")
        private String name;
        
        @Size(max = 200, message = "分组描述不能超过200个字符")
        private String description;
    }
    
    @Data
    public static class ReorderGroupsDto {
        @NotNull(message = "用户ID不能为空")
        private Long userId;
        
        @NotEmpty(message = "分组ID列表不能为空")
        private List<Long> groupIds;
    }
    
    @Data
    public static class MoveFriendDto {
        @NotNull(message = "用户ID不能为空")
        private Long userId;
        
        @NotNull(message = "好友ID不能为空")
        private Long friendId;
        
        private Long groupId; // 可以为null，表示移动到未分组
    }
    
    @Data
    public static class MoveFriendsDto {
        @NotNull(message = "用户ID不能为空")
        private Long userId;
        
        @NotEmpty(message = "好友ID列表不能为空")
        private List<Long> friendIds;
        
        private Long groupId; // 可以为null，表示移动到未分组
    }
    
    @Data
    public static class FriendGroupResponse {
        private Long id;
        private Long userId;
        private String name;
        private String description;
        private Integer sortOrder;
        private Boolean isDefault;
        private Boolean isSystem;
        private LocalDateTime createdAt;
        private LocalDateTime updatedAt;
    }
    
    @Data
    public static class FriendCountResponse {
        private long count;
    }
}